﻿using System;
using System.Device.Location;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
using MapDemo.Resources;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Maps.Controls;
using Microsoft.Phone.Shell;
using Windows.Devices.Geolocation;

namespace MapDemo
{
    public partial class MainPage : PhoneApplicationPage
    {
        GeoCoordinateWatcher watcher;
        private ApplicationBarIconButton appBarBtnStartLocation;
        private ApplicationBarIconButton appBarBtnStopLocation;
        
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            BuildLocalizedApplicationBar();
        }

//<phone:PhoneApplicationPage.ApplicationBar>
//    <shell:ApplicationBar>
//        <shell:ApplicationBarIconButton x:Name="appBarLocation" IconUri="/Assets/questionmark.png" Text="Location" Click="ApplicationBarIconButton_Click_1"/>
//        <shell:ApplicationBarIconButton x:Name="appBarStopLocation" IconUri="/Assets/questionmark.png" Text="Stop" Click="stopLocationButton_Click"/>
            
//    </shell:ApplicationBar>
//</phone:PhoneApplicationPage.ApplicationBar>

        private void BuildLocalizedApplicationBar()
        {
            // Set the page's ApplicationBar to a new instance of ApplicationBar.
            ApplicationBar = new ApplicationBar();

            // Create a new button and set the text value to the localized string from AppResources.
            appBarBtnStartLocation = new ApplicationBarIconButton(new Uri("/Assets/questionmark.png", UriKind.Relative));
            appBarBtnStartLocation.Text = AppResources.AppBarButtonText;
            appBarBtnStartLocation.Click += locationStart_Click;
            ApplicationBar.Buttons.Add(appBarBtnStartLocation);

            //
            appBarBtnStopLocation = new ApplicationBarIconButton(new Uri("/Assets/questionmark.png", UriKind.Relative));
            appBarBtnStopLocation.Text = AppResources.AppBarButtonText;
            appBarBtnStopLocation.Click += stopLocation_Click; 
            ApplicationBar.Buttons.Add(appBarBtnStopLocation);
            

            // Create a new menu item with the localized string from AppResources.
            var appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
            ApplicationBar.MenuItems.Add(appBarMenuItem);
        }

        private async void ShowMyEarthPosition()
        {
            // Get my posistion
            Geolocator myGeolocator = new Geolocator();           
            Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync(); 
            Geocoordinate myGeocoordinate = myGeoposition.Coordinate;

            GeoCoordinate myGeoCoordinate = CoordinateConverter.Convert(myGeocoordinate);

            // Center map to my posistion
            mapMyLocation.Center = myGeoCoordinate; 
            mapMyLocation.ZoomLevel = 13;

            // Make a circle
            var myCircle = new Ellipse {Fill = new SolidColorBrush(Colors.Blue), Height = 20, Width = 20, Opacity = 50};

            // Add circle in own layer
            MapOverlay myLocationOverlay = new MapOverlay(); 
            myLocationOverlay.Content = myCircle; 
            myLocationOverlay.PositionOrigin = new Point(0.5, 0.5); 
            myLocationOverlay.GeoCoordinate = myGeoCoordinate;

            // Show layer together with map
            MapLayer myLocationLayer = new MapLayer(); 
            myLocationLayer.Add(myLocationOverlay); 
            mapMyLocation.Layers.Add(myLocationLayer);
        }

        private void locationStart_Click(object sender, EventArgs e)
        {
            try
            {
                 // The watcher variable was previously declared as type GeoCoordinateWatcher. 
                if (watcher == null)
                {
                    watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // using high accuracy
                    watcher.MovementThreshold = 20; // use MovementThreshold to ignore noise in the signal
                    watcher.StatusChanged += watcher_StatusChanged;
                    watcher.PositionChanged += watcher_PositionChanged;
                    watcher.Start();
                }

                ShowMyEarthPosition();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Feil med kartvisning!" + ex.Message);
            }
        }

        private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            latitudeTextBlock.Text = e.Position.Location.Latitude.ToString("0.000");
            longitudeTextBlock.Text = e.Position.Location.Longitude.ToString("0.000");
        }

        private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    // The Location Service is disabled or unsupported.
                    // Check to see whether the user has disabled the Location Service.
                    if (watcher.Permission == GeoPositionPermission.Denied)
                    {
                        // The user has disabled the Location Service on their device.
                        statusTextBlock.Text = "you have this application access to location.";
                    }
                    else
                    {
                        statusTextBlock.Text = "location is not functioning on this device";
                    }
                    break;

                case GeoPositionStatus.Initializing:
                    // The Location Service is initializing.
                    // Disable the Start Location button.
                    appBarBtnStartLocation.IsEnabled = false;
                    break;

                case GeoPositionStatus.NoData:
                    // The Location Service is working, but it cannot get location data.
                    // Alert the user and enable the Stop Location button.
                    statusTextBlock.Text = "location data is not available.";
                    appBarBtnStopLocation.IsEnabled = true;
                    break;

                case GeoPositionStatus.Ready:
                    // The Location Service is working and is receiving location data.
                    // Show the current position and enable the Stop Location button.
                    statusTextBlock.Text = "location data is available.";
                    appBarBtnStopLocation.IsEnabled = true;
                    break;
            }
        }

        // Click the event handler for the “Start Location” button.
        private void stopLocation_Click(object sender, EventArgs e)
        {
            watcher.Stop();
        }
    }
}